extends Node2D

var sound_players: Array[AudioStreamPlayer]
@onready var sound_player_parent: Node2D = $SoundPlayer

var music_players: Array[AudioStreamPlayer]
@onready var music_player_parent: Node2D = $MusicPlayer


func _ready() -> void:
	sound_players = []
	for index in range(sound_player_parent.get_child_count()):
		sound_players.append(sound_player_parent.get_child(index) as AudioStreamPlayer) 
	
	music_players = []
	for index in range(music_player_parent.get_child_count()):
		music_players.append(music_player_parent.get_child(index) as AudioStreamPlayer) 
		

func play_sound(sound_name: String):
	var player = get_free_snd_player()
	if player:
		player.stream = ResourceManager.get_resource(sound_name)
		player.play()
	return player
		

func get_free_snd_player() -> AudioStreamPlayer:
	for player: AudioStreamPlayer in sound_players:
		if not player.playing:
			return player
	return null
	

func play_music(music_name: String, fade_duration: float = 1.0):
	var player = get_free_music_player()
	if player:
		player.stream = ResourceManager.get_resource(music_name)
		player.volume_db = -40
		player.play()
		
		var tween = create_tween()
		tween.tween_property(player, "volume_db", 0, fade_duration)
	return player
	

func get_free_music_player() -> AudioStreamPlayer:
	for player: AudioStreamPlayer in music_players:
		if not player.playing:
			return player
	return null
	

func stop_all_music():
	for player in music_players:
		if player.playing:
			var tween = create_tween()
			tween.tween_property(player, "volume_db", -40, 1.0)
			tween.tween_callback(Callable(player, "stop"))
